package com.kpmg.datalake.common.utils;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author Alex.zhao [alex.zhao@kpmg.com]
 * Created on azhao6 on 2018-06-22 15:41:24
 */
@Component
public class SpringUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    /**
     * 获取spring的上下文。
     *
     * @return ApplicationContext
     */
    public static ApplicationContext getContext() {
        return applicationContext;
    }

    /**
     * 根据类从spring上下文获取bean。
     *
     * @param cls cls
     * @return Object
     */
    public static <T> T getBean(Class<T> cls) {
        return applicationContext.getBean(cls);
    }

    /**
     * 根据类从spring上下文获取bean。
     *
     * @param beanId beanId
     * @param cls    cls
     * @param <T>    T
     * @return T
     */
    public static <T> T getBean(String beanId, Class<T> cls) {
        return applicationContext.getBean(beanId, cls);
    }

    /**
     * 根据类名从spring上下文获取bean。
     *
     * @param beanId beanId
     * @return Object
     */
    public static Object getBean(String beanId) {
        return applicationContext.getBean(beanId);
    }

    /**
     * spring启动时注入context
     *
     * @param context context
     */
    @Override
    public void setApplicationContext(ApplicationContext context) {
        applicationContext = context;
    }

}
